import React, { useEffect, useRef } from 'react';
import noUiSlider from 'nouislider';
import 'nouislider/dist/nouislider.css';
import './SimpleNoUiSlider.css';

// 基础官方示例
const SimpleNoUiSlider = () => {
  // 统一命名风格的 refs
  const basicSliderRef = useRef(null);
  const rangeSliderRef = useRef(null);
  const stepSliderRef = useRef(null);
  const arraySliderRef = useRef(null);
  const formatSliderRef = useRef(null);
  const colorPickerRef = useRef(null);
  const pipsSliderRef = useRef(null);
  const tooltipSliderRef = useRef(null);
  const colorConnectSliderRef = useRef(null);
  const softLimitSliderRef = useRef(null);
  const resultRef = useRef(null);

  useEffect(() => {
    // 在 effect 内部存储 ref 值
    const basicSlider = basicSliderRef.current;
    const rangeSlider = rangeSliderRef.current;
    const stepSlider = stepSliderRef.current;
    const arraySlider = arraySliderRef.current;
    const formatSlider = formatSliderRef.current;
    const colorPicker = colorPickerRef.current;
    const pipsSlider = pipsSliderRef.current;
    const tooltipSlider = tooltipSliderRef.current;
    const colorConnectSlider = colorConnectSliderRef.current;
    const softLimitSlider = softLimitSliderRef.current;
    const result = resultRef.current;

    // 辅助函数：安全地初始化或销毁 slider
    const initOrDestroySlider = (element, options) => {
      if (element) {
        if (element.noUiSlider) {
          element.noUiSlider.destroy();
        }
        if (options) {
          noUiSlider.create(element, options);
        }
      }
    };

    // 使用这个辅助函数初始化滑块
    if (softLimitSlider) {
      initOrDestroySlider(softLimitSlider, {
        start: 50,
        range: { min: 0, max: 100 },
        pips: {
          mode: 'values',
          values: [20, 80],
          density: 4
        }
      });

      // 添加 change 事件处理软限制
      softLimitSlider.noUiSlider.on('change', function(values, handle) {
        const value = Number(values[handle]);
        if (value < 20) {
          softLimitSlider.noUiSlider.set(20);
        } else if (value > 80) {
          softLimitSlider.noUiSlider.set(80);
        }
      });
    }

    // Example 1: Basic slider
    initOrDestroySlider(basicSlider, {
      start: 80,
      connect: [true, false],
      range: {
        'min': 0,
        'max': 100
      }
    });

    // Example 2: Range slider
    initOrDestroySlider(rangeSlider, {
      start: [20, 80],
      connect: true,
      range: {
        'min': 0,
        'max': 100
      }
    });

    // Example 3: Slider with steps
    initOrDestroySlider(stepSlider, {
      start: [50],
      connect: [true, false],
      step: 10,
      range: {
        'min': 0,
        'max': 100
      }
    });

    // Example 4: Using array values
    const valuesForSlider = [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32];
    const format = {
      to: function(value) {
        return valuesForSlider[Math.round(value)];
      },
      from: function(value) {
        return valuesForSlider.indexOf(Number(value));
      }
    };

    initOrDestroySlider(arraySlider, {
      start: [8, 24],
      range: { min: 0, max: valuesForSlider.length - 1 },
      step: 1,
      tooltips: true,
      format: format,
      pips: { mode: 'steps', format: format }
    });

    // Example 5: Number formatting
    const formatForSlider = {
      from: function(formattedValue) {
        return Number(formattedValue);
      },
      to: function(numericValue) {
        return Math.round(numericValue);
      }
    };

    initOrDestroySlider(formatSlider, {
      start: ['20.0', '80.0'],
      range: {
        'min': 0,
        'max': 100
      },
      format: formatForSlider,
      tooltips: {
        to: function(numericValue) {
          return numericValue.toFixed(1);
        }
      }
    });

    // Example 6: Color picker
    if (colorPicker) {
      const sliders = colorPicker.querySelectorAll('.color-slider');
      const colors = [0, 0, 0];
      
      // 先销毁所有已存在的实例
      sliders.forEach(slider => {
        if (slider.noUiSlider) {
          slider.noUiSlider.destroy();
        }
      });

      // 然后创建新实例
      sliders.forEach((slider, index) => {
        noUiSlider.create(slider, {
          start: 127,
          connect: [true, false],
          orientation: "vertical",
          range: {
            'min': 0,
            'max': 255
          },
          format: {
            to: function(value) {
              return Math.round(value);
            },
            from: function(value) {
              return Number(value);
            }
          }
        });

        // 绑定颜色更新事件
        slider.noUiSlider.on('update', function() {
          colors[index] = slider.noUiSlider.get();
          if (result) {
            const color = `rgb(${colors.join(',')})`;
            result.style.background = color;
            result.style.color = color;
          }
        });
      });
    }

    // Example 7: Interacting with Pips
    initOrDestroySlider(pipsSlider, {
      start: 50,
      range: { min: 0, max: 100 },
      pips: { mode: 'count', values: 5 }
    });

    // Example 8: Tooltips Only When Sliding
    initOrDestroySlider(tooltipSlider, {
      start: 40,
      range: { min: 0, max: 100 },
      tooltips: true
    });

    // Example 9: Colored Connect Elements
    initOrDestroySlider(colorConnectSlider, {
      start: [4000, 8000, 12000, 16000],
      connect: [false, true, true, true, true],
      range: {
        'min': [2000],
        'max': [20000]
      }
    });

    // 为连接元素添加颜色类
    if (colorConnectSlider && colorConnectSlider.noUiSlider) {
      const connect = colorConnectSlider.querySelectorAll('.noUi-connect');
      const classes = ['c-1-color', 'c-2-color', 'c-3-color', 'c-4-color', 'c-5-color'];
      connect.forEach((el, index) => {
        el.classList.add(classes[index]);
      });
    }

    // Example 10: Soft Limits
    initOrDestroySlider(softLimitSlider, {
      start: 50,
      range: {
        min: 0,
        max: 100
      },
      pips: {
        mode: 'values',
        values: [20, 80],
        density: 4
      }
    });

    // 为 softLimitSlider 添加 change 事件处理软限制
    if (softLimitSlider && softLimitSlider.noUiSlider) {
      softLimitSlider.noUiSlider.on('change', function(values, handle) {
        const value = Number(values[handle]);
        if (value < 20) {
          softLimitSlider.noUiSlider.set(20);
        } else if (value > 80) {
          softLimitSlider.noUiSlider.set(80);
        }
      });
    }

    // Cleanup function
    return () => {
      // 统一清理所有滑块实例
      [
        basicSlider, rangeSlider, stepSlider, arraySlider, formatSlider,
        pipsSlider, tooltipSlider, colorConnectSlider, softLimitSlider
      ].forEach(slider => {
        if (slider && slider.noUiSlider) {
          slider.noUiSlider.destroy();
        }
      });

      // 特别处理颜色选择器
      if (colorPicker) {
        const sliders = colorPicker.querySelectorAll('.color-slider');
        sliders.forEach(slider => {
          if (slider.noUiSlider) {
            slider.noUiSlider.destroy();
          }
        });
      }
    };
  }, []); // 空依赖数组确保 effect 只运行一次

  return (
    <div className="slider-examples">
      <div className="explanation-box">
        <p>⚠️ 注意：此页面展示的是 noUiSlider 的简易封装示例，直接使用 noUiSlider 的原生 API。</p>
        <p>其他示例页面使用的是封装好的 NoUiSlider React 组件，提供了更完整的 React 集成功能。</p>
      </div>

      <div className="example-container">
        <h2>Example 1: Basic Slider</h2>
        <div ref={basicSliderRef} className="basic-slider"></div>
        <p className="example-description">最基础的滑块示例，展示单个滑块的创建和使用</p>
      </div>

      <div className="example-container">
        <h2>Example 2: Range Slider</h2>
        <div ref={rangeSliderRef} className="range-slider"></div>
        <p className="example-description">双滑块范围选择器，可以同时选择最小值和最大值</p>
      </div>

      <div className="example-container">
        <h2>Example 3: Slider with Steps</h2>
        <div ref={stepSliderRef} className="step-slider"></div>
        <p className="example-description">带有固定步长的滑块，每次移动都会按照设定的步长（10）进行</p>
      </div>

      <div className="example-container">
        <h2>Example 4: Using Array Values</h2>
        <div ref={arraySliderRef} className="array-slider"></div>
        <p className="example-description">使用预定义的值数组，滑块只能选择这些值</p>
      </div>

      <div className="example-container">
        <h2>Example 5: Number Formatting</h2>
        <div ref={formatSliderRef} className="format-slider"></div>
        <p className="example-description">展示数字格式化，滑块值取整，工具提示保留一位小数</p>
      </div>

      <div className="example-container">
        <h2>Example 6: Color Picker</h2>
        <div ref={colorPickerRef} className="color-picker">
          <div className="color-slider red"></div>
          <div className="color-slider green"></div>
          <div className="color-slider blue"></div>
          <div ref={resultRef} className="color-result"></div>
        </div>
        <p className="example-description">使用三个垂直滑块控制 RGB 颜色值</p>
      </div>

      <div className="example-container">
        <h2>Example 7: Interacting with Pips</h2>
        <div ref={pipsSliderRef} className="pips-slider"></div>
        <p className="example-description">点击刻度值可以直接跳转到对应位置</p>
      </div>

      <div className="example-container">
        <h2>Example 8: Tooltips Only When Sliding</h2>
        <div ref={tooltipSliderRef} className="tooltip-slider"></div>
        <p className="example-description">只有在滑动时才显示提示框</p>
      </div>

      <div className="example-container">
        <h2>Example 9: Colored Connect Elements</h2>
        <div ref={colorConnectSliderRef} className="color-connect-slider"></div>
        <p className="example-description">展示如何为连接元素设置不同的颜色</p>
      </div>

      <div className="example-container">
        <h2>Example 10: Soft Limits</h2>
        <div ref={softLimitSliderRef} className="soft-limit-slider"></div>
        <p className="example-description">设置软限制：当值超出20-80范围时会自动弹回</p>
      </div>
    </div>
  );
};

export default SimpleNoUiSlider; 